package cn.cvs.dao;

import cn.cvs.utils.ConfigManager;

import java.sql.*;

public class BaseDao {
//    static String driver="com.mysql.cj.jdbc.Driver";
//    static String url="jdbc:mysql://localhost:3306/exam?serverTimezone=GMT-8&useUnicode=true&characterEncoding=utf-8" ;
//    static String username="root" ;
//    static String password="root";

    protected Connection conn = null;
    protected PreparedStatement pstmt = null;
    protected ResultSet rs = null;

    /**
     * 获取连接
     * @return
     */
    public Connection getConnection(){
        Connection conn = null;
        String driver= ConfigManager.getInstance().getValue("driver");
        String url=ConfigManager.getInstance().getValue("url");
        String user=ConfigManager.getInstance().getValue("user");
        String password=ConfigManager.getInstance().getValue("password");
        // 建立连接，获取连接对象，要指定 连接字符串等
        try {
            Class.forName(driver);
            conn=DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 释放资源
     * @param conn
     * @param stmt
     * @param rs
     */
    public void closeAll(Connection conn, Statement stmt, ResultSet rs){
        try {
            if (rs!=null){
                rs.close();
            }
            if (stmt!=null){
                stmt.close();
            }
            if (conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
